package com.senlingspace.payment.config.properties;

import com.senlingspace.common.exception.payment.LakalaException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.FileCopyUtils;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * 拉卡拉配置
 *
 * @author lebronjames
 * @date 2024/07/15
 */
@Slf4j
@Data
@Configuration
@ConfigurationProperties(prefix = "lakala")
public class LakalaProperties {

    // 拉卡拉开放平台进行配置开通
    private String appId;

    // 商户证书序列号,和商户私钥对应
    private String serialNo;

    // 商户私钥地址,用于请求签名
    private String privateKey;

    // 拉卡拉支付平台证书地址
    private String lklCer;

    //  拉卡拉支付平台证书地址2(用于拉卡拉通知验签，证书与lklCerPath)一致，测试证书为：lkl-apigw-v2.cer）
    private String lklNotifyCer;

    // 拉卡拉开放平台服务地址
    private String serverUrl;

    // 自身服务 IP
    private String serverIpAddress;

    // 在构造函数之后执行，初始化配置
    @PostConstruct
    public void init() {
        try {
            log.info("拉卡拉证书文件加载中...");
            this.privateKey = loadFileContent(this.privateKey);
            this.lklCer = loadFileContent(this.lklCer);
            this.lklNotifyCer = loadFileContent(this.lklNotifyCer);
        } catch (IOException e) {
            throw new LakalaException("拉卡拉证书文件加载失败: " + e.getMessage());
        }

        try {
            log.info("解码平台自身IP...");
            byte[] ipBytes = Base64.getDecoder().decode(this.serverIpAddress);
            InetAddress inetAddress = InetAddress.getByAddress(ipBytes);
            this.serverIpAddress = inetAddress.getHostAddress();
        } catch (UnknownHostException e) {
            throw new LakalaException("解码平台自身IP失败: " + e.getMessage());
        }

        log.info("校验参数信息...");
        validateConfiguration();

        log.info("拉卡拉配置初始化完成！");
    }

    private void validateConfiguration() {
        if (StringUtils.isBlank(this.appId)) {
            throw new LakalaException("拉卡拉 AppId 不能为空！");
        }

        if (StringUtils.isBlank(this.serialNo)) {
            throw new LakalaException("拉卡拉证书序列号不能为空！");
        }

        if (StringUtils.isBlank(this.serverIpAddress)) {
            throw new LakalaException("平台自身 IP 不能为空！");
        }
    }

    private String loadFileContent(String filename) throws IOException {
        ClassPathResource resource = new ClassPathResource(filename);
        byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream());
        return new String(bytes, StandardCharsets.UTF_8);
    }

}
